/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.danlu.dlsms.model.pub.res.MsgCountResponse;

import java.util.Map;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.constant.MsgTypeConst;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.PreferenceUtils;
import cn.com.dhc.danlu.util.TipCountUtil;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.holder.MyselfHolder;
import cn.com.dhc.danlu.widget.holder.MyselfHolder.OnEventTransfer;
import cn.com.dhc.danlu.yijifu.YjfPayEngine;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetAllCouponCntResponse;
import cn.com.hd.mall.web.webservices.entity.request.account.GetCompanyInfoRequest;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.GetUnreadCountRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.account.GetCompanyInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderCountResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-11-07 04:20<br/>
 * <p>
 * <p>
 * 我的丹露页面
 * </p>
 */
public class MyselfActivity extends BaseActivity implements OnEventTransfer {
    private MyselfHolder selfHolderView;
    private YjfPayEngine yjfPayEngine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myself);

        selfHolderView = new MyselfHolder(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0));
        selfHolderView.setEventCallback(this);
        selfHolderView.bindAction();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 获取订单数量
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi().getTerminalOrderCount(request).compose(OperatorUtils.<OrderCountResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<OrderCountResponse>() {
                    @Override
                    protected void onSuccess(OrderCountResponse orderCountResponse) {
                        selfHolderView.refreshBadge(orderCountResponse);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "订单数量获取失败！" : displayMessage);
                    }
                });

        // 从其他分支merge 可能需要去获取收藏相关数据 || 未读消息数量 | 根据companyId 获取终端店信息
        // 我的红包数量
        getEnvelopCount();
        // 未读消息数量
        getUnreadMsgCountRequest();
        // 企业信息在onCreate方法中获取了
        getCompanyInfo();// 测试人员需要及时刷新
    }

    // 刷新丹露红包、经销商红包和经销商优惠券的数量 lyf
    private void getEnvelopCount() {
        agent.getApi().getAllCouponCnt(new cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest(agent.getToken()))
                .compose(OperatorUtils.<GetAllCouponCntResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetAllCouponCntResponse>() {
                    @Override
                    protected void onSuccess(GetAllCouponCntResponse getAllCouponCntResponse) {
                        selfHolderView.tv_danlu_envelop_count.setText(TipCountUtil.cover(getAllCouponCntResponse.getDanluCouponCnt(), TipCountUtil.SMALL_FLAG));
                        selfHolderView.tv_dealer_envelop_count.setText(TipCountUtil.cover(getAllCouponCntResponse.getDealerCouponCnt(), TipCountUtil.SMALL_FLAG));
                        selfHolderView.tv_dealer_coupon_count.setText(TipCountUtil.cover(getAllCouponCntResponse.getDealerBenefitCnt(), TipCountUtil.SMALL_FLAG));
                    }
                });
    }

    /**
     * 获取未读取消息数量
     */
    private void getUnreadMsgCountRequest() {
        GetUnreadCountRequest request = new GetUnreadCountRequest();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.channelId = CommonConst.CHANNEL_ID;

        agent.getMsgApi().getUnreadMsgCount(request).compose(OperatorUtils.<MsgCountResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<MsgCountResponse>() {
                    @Override
                    protected void onSuccess(MsgCountResponse msgCountResponse) {
                        Map<String, Integer> unreadMap = msgCountResponse.getMsgCount().getUnreadCount();
                        int unreadOrderMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.PURCHASE_ORDER_MSG);
                        int unreadOtherMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.MY_MSG);
                        // 未读红包消息数量
                        int unreadEnvelopMsg = 0;
                        if (null != unreadMap.get(MsgTypeConst.MsgTypeGroup.DANLU_ENVELOP_MSG)) {
                            unreadEnvelopMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.DANLU_ENVELOP_MSG);
                        }
                        refreshMsgCount(unreadOrderMsg + unreadOtherMsg + unreadEnvelopMsg);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "未读消息数量获取失败！" : displayMessage);
                    }
                });
    }

    /**
     * 获取企业信息
     */
    private void getCompanyInfo() {
        GetCompanyInfoRequest request = new GetCompanyInfoRequest();
        request.setToken(agent.getToken());
        request.setCompanyId(agent.getLoginUser().getCompanyId());
        agent.getApi().getCompanyInfo(request).compose(OperatorUtils.<GetCompanyInfoResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetCompanyInfoResponse>() {
                    @Override
                    protected void onSuccess(GetCompanyInfoResponse getCompanyInfoResponse) {
                        refreshCompanyInfoUI(getCompanyInfoResponse);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "用户信息获取失败！" : displayMessage);
                    }
                });
    }

    protected void refreshMsgCount(int i) {
        selfHolderView.refreshMsgBadge(i);
    }

    protected void refreshCompanyInfoUI(GetCompanyInfoResponse response) {
        selfHolderView.tv_account.setText(response.getUserAcct());
        String terminalName = response.getCompanyName();
        if (!TextUtils.isEmpty(terminalName)) {
            if (terminalName.length() > 10) {
                terminalName += "....";
            }
            selfHolderView.tvTerminalName.setText(terminalName);
        } else {
            selfHolderView.tvTerminalName.setText("未命名");
        }
        selfHolderView.tvSaleTypeLocation.setText(response.getTerminalType() + " (" + response.getPurchaseAreaName() + ")");
    }

    @Override
    public void performClickBinkCard() {
        // 跳转支付渠道选择界面 lyf 2016-11-08 16:38:35  联动优势代码
        // add by llq 删除联动优势功能，暂时处理办法
        if (null == yjfPayEngine) {
            yjfPayEngine = new YjfPayEngine(this, null, true);
        }
        yjfPayEngine.getYjfConfig();
    }

    @Override
    public PreferenceUtils getPrefrenceUtil() {
        return getPreferenceUtils();
    }
}
